package com.lzc.springBootPart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import java.util.Collections;

@Configuration
@ComponentScan
public class SpringBootTest {

    @Bean
    public DispatcherServlet dispatcherServlet(){
        return new DispatcherServlet();
    }

    @SuppressWarnings("all")
    public static void main(String[] args) {

        SpringApplication.run(SpringBootTest.class);

        SpringApplication application = new SpringApplication();
        application.setInitializers(Collections.singleton(new ApplicationContextInitializer<ConfigurableApplicationContext>() {
            @Override
            public void initialize(ConfigurableApplicationContext applicationContext) {
                System.out.println("执行初始化器");
            }
        }));

        /**----------------------------------初始化开始过程----------------------------------------**/
        System.out.println("--------创建容器---------");
        // 根据容器创建实现
        GenericApplicationContext context = new AnnotationConfigServletWebServerApplicationContext();
        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }

        System.out.println("--------准备容器(加载 工厂后置处理器  bean后置处理器 的beanDefinition)---------");
        // 回调初始化器
        for (ApplicationContextInitializer initializer : application.getInitializers()) {
            initializer.initialize(context);
        }

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }

        System.out.println("--------加载主类 bean定义--------");
        // 加载bean定义
        AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(context);
        reader.register(SpringBootTest.class);

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }

        System.out.println("--------创建容器-（执行beanFactory后置处理器 和 bean后置处理器）--------");

        context.refresh();
        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }

        /*--------------------------------------------------初始化结束----------------------------------------------------------*/
    }
}
